﻿using System;
using System.Linq;
using System.Windows.Data;

namespace ForumsBrowser
{
    public class DateTimeTextConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
           
            if (value != null && (value is DateTime || value is DateTime?))
            {
                DateTime date = (DateTime)value;
                DateTime now = DateTime.Now;

                if (date == DateTime.MinValue)
                    return string.Empty;

                if (date > now.AddMinutes(-1))
                    return "Just now...";
                else if (date > now.AddHours(-1))
                {
                    var i = now.Subtract(date).Minutes;
                    return string.Format("{0} minute{1} ago", i, i > 1 ? "s" : string.Empty);
                }
                else if (date > now.AddDays(-1))
                {
                    var i = now.Subtract(date).Hours;
                    return string.Format("{0} hour{1} ago", i, i > 1 ? "s" : string.Empty);
                }
                else if (date > now.AddMonths(-1))
                {
                    var i = now.Subtract(date).Hours;
                    return string.Format("{0} day{1} ago", i, i > 1 ? "s" : string.Empty);
                }
                else if (date > now.AddYears(-1))
                {
                    int i = 0;
                    while ((now = now.AddMonths(-1)) > date)
                    {
                        i++;
                    }

                    return string.Format("Over {0} month{1} ago", i, i > 1 ? "s" : string.Empty);
                }
                else
                {
                    int i = 0;

                    while ((now = now.AddYears(-1)) > date)
                    {
                        i++;
                    }

                    return string.Format("Over {0} year{1} ago", i, i > 1 ? "s" : string.Empty);
                }

            }
            return string.Empty;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    }
}
